<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="8">
        <div class="app-container">
          <el-row class="relationContainer">
            <el-col :span="8"><span class="el-custom-title">动素类型</span></el-col>
            <el-col :span="16" style="float: right">
              <el-button-group>
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                 size="mini"
                  @click="handleCreate"
                  >添加</el-button
                >
                <el-button type="primary"
                 icon="el-icon-edit"
                 size="mini" @click="handleUpdate()">
                  编辑
                </el-button>
                <el-button
                  size="mini"
                  type="danger"
                   icon="el-icon-delete"
                  @click="deleteActionTherbligsType(null, null)"
                >
                  删除
                </el-button>
              </el-button-group>
            </el-col>
          </el-row>
          <el-row type="flex" justify="start">
            <el-table
              v-loading="listLoading"
              :data="list"
              element-loading-text="Loading"
              border
              fit
              highlight-current-row
              @row-click="rowClick"
              @selection-change="handleSelectionChange"
            >
              >
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column
                align="center"
                label="序号"
                width="95"
                v-if="false"
              >
                <template slot-scope="scope">
                  {{ scope.row.id }}
                </template>
              </el-table-column>
              <el-table-column label="编号">
                <template slot-scope="scope">
                  {{ scope.row.therbligsTypeNo }}
                </template>
              </el-table-column>
              <el-table-column label="名称">
                <template slot-scope="scope">
                  {{ scope.row.therbligsTypeName }}
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </div>
      </el-col>
      <el-col :span="16">
        <div class="app-container">
          <el-row class="relationContainer">
            <el-col :span="8"><span class="el-custom-title">动素管理</span>
            </el-col>
                    <el-col :span="16" style="float:right;">
            <el-button-group style="float: right">
              <el-button
                type="primary"
                icon="el-icon-plus"
                class="el-button--mini"
                @click="handleCreateSon"
                >添加</el-button
              >
              <el-button type="primary" round
               icon="el-icon-edit"
               size="mini" @click="handleUpdateSon()">
                编辑
              </el-button>
              <el-button
                size="mini"
                type="danger"
                 icon="el-icon-delete"
                @click="ui_delete(null,null)"
              >
                删除
              </el-button>
            </el-button-group>
            </el-col>
          </el-row>
          <el-row type="flex" justify="start">
            <el-table
              v-loading="listLoading"
              :data="list2"
              element-loading-text="Loading"
              border
              fit
              highlight-current-row
              @selection-change="handleSelectionChangeSon"
              >
            >
            <el-table-column
            type="selection"
             width="55"
            ></el-table-column>
                <el-table-column align="center" label="动素编号" width="95" style="display:none;">
                <template slot-scope="scope">
                  {{ scope.row.therbligsNo }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="动素名称" width="95" style="display:none;">
                <template slot-scope="scope">
                  {{ scope.row.therbligsName }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="动素类型" width="95" style="display:none;">
                <template slot-scope="scope">
                  {{ scope.row.therbligsTypeNo }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="动素类型" width="95" style="display:none;">
                <template slot-scope="scope">
                  {{ scope.row.therbligsTypeName }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="mod值" width="95" style="display:none;">
                <template slot-scope="scope">
                  {{ scope.row.modValue }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="mod时间" width="95" style="display:none;">
                <template slot-scope="scope">
                  {{ scope.row.modTime }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="备注" width="95" style="display:none;">
                <template slot-scope="scope">
                  {{ scope.row.comment }}
                </template>
              </el-table-column>
            </el-table>
          </el-row>
            <el-row>
 <pagination
            v-show="total2 > 0"
            :total="total2"
            :page.sync="listQuery2.page"
            :limit.sync="listQuery2.limit"
            :page-sizes="listQuery2.pageSizes"
            @pagination="getTherbligs"
          />
              
              </el-row>
        </div>
      </el-col>
    </el-row>
      <el-dialog :title="textMap[dialogStatusSon]" :visible.sync="dialogFormVisibleSon">
      <el-form
        ref="dataFormson"
        :rules="rulesson"
        :model="tempson"
        label-position="left"
        label-width="120px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="动素编号" prop="therbligsNo">
          <el-input v-model="tempson.therbligsNo" />
        </el-form-item>
        <el-form-item label="动素名称" prop="therbligsName">
          <el-input v-model="tempson.therbligsName" />
        </el-form-item>
        <el-form-item label="动素类型" prop="therbligsTypeId">
            <el-select v-model="tempson.therbligsTypeId" class="filter-item" placeholder="请选择动素类型" @change="handleMainTypeChange">
            <el-option v-for="item in this.ddActionSibligTypes" :key="item.id" :label="item.therbligsTypeName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="mod值" prop="modValue">
          <el-input v-model="tempson.modValue" />
        </el-form-item>
        <el-form-item label="mod时间" prop="modTime">
          <el-input v-model="tempson.modTime" />
        </el-form-item>
        <el-form-item label="备注" prop="comment">
          <el-input v-model="tempson.comment" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleSon = false"> 取消 </el-button>
        <el-button
          type="primary"
          @click="
            dialogStatusSon === 'create'
              ? ui_create()
              : ui_update()
          "
        >
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="120px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="动素类型编号" prop="therbligsTypeNo">
          <el-input v-model="temp.therbligsTypeNo" />
        </el-form-item>
        <el-form-item label="动素类型名称" prop="therbligsTypeName">
          <el-input v-model="temp.therbligsTypeName" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button
          type="primary"
          @click="
            dialogStatus === 'create'
              ? createActionTherbligsType()
              : updateActionTherbligsType()
          "
        >
          确定
        </el-button>
      </div>
    </el-dialog>
    <router-view></router-view>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import request from "@/utils/request";
import {
  getAllActionTherbligsTypes,
  getTherbligsType,
  createTherbligsType,
  updateTherbligsType,
  deleteTherbligsType,
  deleteTherbligsTypes,
} from "@/api/mesActionTherbligsType";

import {
  getAllSon,
  listSon,
  createSon,
  updateSon,
  deleteBatchSon,
} from "@/api/mesActionTherbligs";

export default {
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger",
      };
      return statusMap[status];
    },
  },
  data() {
      const validateActionSibligType = (rule, value, callback) => {
       let val = parseInt(value)
      if (val == null || val<1) {
        callback(new Error('请选择动素类型!'))
      } else {
        callback()
      }
    }
    return {
      filterText: "",
      data2: [],
      defaultProps: {
        children: "children",
        label: "TherbligsTypeTypeName",
      },
      list: [],
      list2: [],
      listLoading: true,
      total2: 0,
      listQuery2: {
        page: 1,
        limit: 6,
        pageSizes: [6, 10, 14],
      },
      currentTherbligsTypeId: 0,
      dialogFormVisible: false,
      dialogFormVisibleSon: false,
      dialogStatus: "",
       dialogStatusSon: "",
      textMap: {
        update: "编辑",
        create: "创建",
      },
      rules: {
        therbligsTypeNo: [
          {
            required: true,
            message: "动素类型参数编号不能为空！",
            trigger: "change",
          },
        ],
        therbligsTypeName: [
          {
            required: true,
            message: "动素类型参数名称不能为空！",
            trigger: "blur",
          },
        ],
      },
       rulesson: {
        therbligsNo: [
          {
            required: true,
            message: "动素编号不能为空！",
            trigger: "change",
          },
        ],
        therbligsName: [
          {
            required: true,
            message: "动素名称不能为空！",
            trigger: "change",
          },
        ],
        therbligsTypeId: [
          {
            required: true,
            message: "动素类型不能为空！",
            trigger: "change",
            validator:validateActionSibligType
          },
        ],
        modValue: [
          {
            required: true,
            message: "mod值不能为空！",
            trigger: "change",
          },
        ],
        modTime: [
          {
            required: true,
            message: "mod时间不能为空！",
            trigger: "change",
          },
        ]
      },
      temp: {
        id: undefined,
        therbligsTypeParaNo: "",
        therbligsTypeTypeName: "",
        comment: "",
      },
      tempson: {
       id: undefined,
       therbligsNo : '',
       therbligsName : '',
       therbligsTypeId : 0,
       modValue : '',
       modTime : '',
       comment : '',
      },
      //表格變量
      lstSelected: [],
      lstSelectedSon: [],
      ddActionSibligTypes:[],
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree2.filter(val);
    },
  },
  computed: {
     
  },
  created() {
    this.fetchData();
    this.getTherbligs();
  },
  methods: {
    handleSelectionChange(val) {
      this.lstSelected = val;
    },
     handleSelectionChangeSon(val) {
       if(val == null || val.length  == 0 ) return
      this.lstSelectedSon = val
      const type = this.list.find((v) => v.therbligsTypeNo === val[0].therbligsTypeNo)
      if(type != null)
      {
        this.currentTherbligsTypeId = type.id
      }
    },
    fetchData() {
      this.listLoading = true;
      let params = {
        name: "",
      };
      getAllActionTherbligsTypes(params).then((response) => {
        this.list = response.data;
        if(this.list != null && this.list.length > 0){
          this.list.map(v=>{
               this.ddActionSibligTypes.push({id:v.id,therbligsTypeName:v.therbligsTypeName});
          })
        }
        this.ddActionSibligTypes.splice(0,0,{id:0,therbligsTypeName:"请选择"})
        this.listLoading = false;
      });
    },

    getTherbligs() {
      let params = {
        name: this.currentTherbligsTypeId,
        page: this.listQuery2.page,
        size: this.listQuery2.limit,
      };
      return listSon(params).then((response) => {
        this.list2 = response.data.records;
       // console.log(this.list2);
        this.total2 = response.data.total;
        this.listLoading = false;
      });
    },
    rowClick(row, column, event) {
      this.currentTherbligsTypeId = row.id;
      this.getTherbligs();
    },
    createActionTherbligsType() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.temp.id = 0; //自增
          createTherbligsType(this.temp).then(() => {
            this.list.unshift(this.temp);
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "添加成功！",
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    updateActionTherbligsType() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          updateTherbligsType(this.temp).then(() => {
            const index = this.list.findIndex((v) => v.id === this.temp.id);
            this.list.splice(index, 1, this.temp);
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "修改成功！",
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    deleteActionTherbligsType(row, index) {
      if (this.lstSelected == null || this.lstSelected.length === 0) {
        this.$message.error("请先选择要删除的动素类型");
        return;
      }
      let ids = [];
      this.lstSelected.map(function (elm) {
        ids.push(elm.id);
      });
      deleteTherbligsTypes(ids).then(() => {
        ids.forEach((elm) => {
          const index = this.list.findIndex((v) => v.id === elm);
          this.list.splice(index, 1);
        });

        this.dialogFormVisible = false;
        this.$notify({
          title: "Success",
          message: "删除成功！",
          type: "success",
          duration: 2000,
        });
      });
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        TherbligsTypeParaNo: "",
        TherbligsTypeTypeName: "",
        TherbligsTypeId: 0,
      };
    },
     resetTempSon() {
      this.temp = {
              id: undefined,
              therbligsNo : '',
              therbligsName : '',
              therbligsTypeId : 0,
              modValue : '',
              modTime : '',
              comment : '',
      }
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleUpdate() {
      if (this.lstSelected == null || this.lstSelected.length !== 1) {
        this.$message.error("请先选择一条动素类型");
        return;
      }
      this.temp = Object.assign({}, this.lstSelected[0]); // copy obj
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
     handleCreateSon() {
      this.resetTempSon()
      this.dialogStatusSon = "create"
      this.dialogFormVisibleSon = true
      this.$nextTick(() => {
        this.$refs["dataFormson"].clearValidate()
      })
    },
    handleUpdateSon() {
      if(this.lstSelectedSon == null || this.lstSelectedSon.length !==1)
      {
         this.$message.error('请先选择一条动素记录')
         return
      }
      this.tempson = Object.assign({}, this.lstSelectedSon[0]); // copy obj
      this.tempson.therbligsTypeId = this.currentTherbligsTypeId
      this.tempson = {... this.tempson}
      this.dialogStatusSon = "update"
      this.dialogFormVisibleSon = true
      this.$nextTick(() => {
        this.$refs["dataFormson"].clearValidate()
      })
    },
     ui_create() {
      this.$refs["dataFormson"].validate((valid) => {
        if (valid) {
          this.tempson.id = 0; //自增
          createSon(this.tempson).then(() => {
            this.list2.unshift(this.tempson)
            this.dialogFormVisibleSon = false
            this.$notify({
              title: "Success",
              message: "添加成功！",
              type: "success",
              duration: 2000,
            })
          })
        }
      })
    },
    ui_update() {
     
      this.$refs["dataFormson"].validate((valid) => {
        if (valid) {
          updateSon(this.tempson).then(() => {
            const index = this.list2.findIndex((v) => v.id === this.tempson.id)
            this.list2.splice(index, 1, this.tempson)
            this.dialogFormVisibleSon = false
            this.$notify({
              title: "Success",
              message: "修改成功！",
              type: "success",
              duration: 2000,
            })
          })
        }
      });
    },
    ui_delete(row, index) {
       if(this.lstSelectedSon == null || this.lstSelectedSon.length === 0)
      {
         this.$message.error('请先选择要删除的ActionTherbligs')
         return
      }
      let ids = []
      this.lstSelectedSon.map(function(elm){
         ids.push(elm.id)
      })
      deleteBatchSon(ids).then(() => {
        ids.forEach((elm) => {
         const index = this.list2.findIndex((v) => v.id === elm)
         this.list2.splice(index, 1)
        })
       
        this.dialogFormVisibleSon = false
        this.$notify({
          title: "Success",
          message: "删除成功！",
          type: "success",
          duration: 2000,
        })
      })
    },
    handleMainTypeChange(val)
    {
       this.tempson.therbligsTypeId = val
       this.tempson = {... this.tempson}
    },
  },
};
</script>
<style>
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}

</style>
